package com.micklebes.dao.impl;

import com.google.appengine.api.datastore.Key;
import com.micklebes.dao.GenericDAO;

import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

/**
 * User: Catalin
 * Date: 8/7/11
 * Time: 11:59 PM
 */
public class GenericDAOImpl<T> implements GenericDAO<T> {

    protected PersistenceManagerFactory pmf;

    public PersistenceManager getPersistenceManager() {
        return pmf.getPersistenceManager();
    }

    public void setPmf(PersistenceManagerFactory pmf) {
        this.pmf = pmf;
    }

    private Class<T> persistentClass;

    @SuppressWarnings("unchecked")
    public GenericDAOImpl() {
        persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }

    public T createObject(T object) {
        PersistenceManager persistenceManager = getPersistenceManager();
        persistenceManager.makePersistent(object);
        persistenceManager.close();
        return object;
    }

    public void deleteObject(T object) {
        PersistenceManager persistenceManager = getPersistenceManager();
        persistenceManager.deletePersistent(object);
        persistenceManager.close();
    }

    public T findObjectById(Serializable id) {
        PersistenceManager persistenceManager = getPersistenceManager();
        T result = persistenceManager.getObjectById(persistentClass, id);
        persistenceManager.close();
        return result;
    }

    public void flush() {
        PersistenceManager persistenceManager = getPersistenceManager();
        persistenceManager.flush();
        persistenceManager.close();
    }


    public T updateObject(T object) {
        PersistenceManager persistenceManager = getPersistenceManager();
        persistenceManager.makePersistent(object);
        persistenceManager.close();
        return object;

    }

    @SuppressWarnings("unchecked")
    public List<T> findAll() {
        PersistenceManager persistenceManager = getPersistenceManager();
        List<T> results = (List<T>) persistenceManager.newQuery(persistentClass).execute();
        results.size();
        persistenceManager.close();
        return results;
    }

    public T getByKey(Key key) {
        PersistenceManager persistenceManager = getPersistenceManager();
        T result = persistenceManager.getObjectById(persistentClass, key);
        persistenceManager.close();

        return result;
    }
}